import ApiFetchers from "@/apis/api_fetchers"
import { RefGameListItem, RefGetGameListQuery } from "@/apis/home_page_constant_types"
import { homeGamesAtom } from "@/features/business/HomePage_deprecated/atoms_deprecated"
import { extractIds, getGameTypeBySection } from "@/features/business/HomePage_deprecated/constant"
import { useSearchActionWithKey } from "@/features/useSearchActionWithKey"
import { useRequest, useUpdateEffect } from "ahooks"
import { useAtom } from "jotai"
import { isString } from "lodash"
import { useEffect, useMemo, useState } from "react"
import { useParams } from "react-router-dom"
import { usePaginatedList } from "./usePaginatedRequest"

export function useSubPage() {
    const { categoryId = "" } = useParams<{
        categoryId: string
    }>()

    const { getActionList, setAction } = useSearchActionWithKey()
    const [sort = "", brands = ""] = getActionList(["sort", "brands"])
    const [keyword, setKeyword] = useState<string>("")
    const [{ links }] = useAtom(homeGamesAtom)

    const providerList = useMemo(() => {
        return links[categoryId] ?? []
    }, [links, categoryId])

    const { venueIds = [], platformIds = [] } = extractIds(
        isString(brands) ? brands.split(",") : [],
    )

    useEffect(() => {
        /**
         * 检查参数是否在该列表中, 不存在说明后台关闭了, 需要移除
         */
        if (providerList.length && brands?.length) {
            const existBrands: string[] = []
            const brandsArr = isString(brands) ? brands.split(",") : []
            brandsArr.forEach((brand) => {
                if (
                    providerList.some((provider) => brand === `${provider.venue_id}_${provider.id}`)
                ) {
                    existBrands.push(brand)
                }
            })
            setAction("brands", existBrands.join(","))
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [providerList, brands])

    const sorting = useMemo(() => {
        if (sort?.toLowerCase() === "popular") {
            return "sorting:asc"
        }
        if (sort?.toLowerCase() === "a-z") {
            return "en_name:asc"
        }
        return ""
    }, [sort])

    const { list, loading, noMore, reload, loadMore } = usePaginatedList<
        RefGetGameListQuery,
        RefGameListItem
    >({
        initialQuery: {
            sorting,
            venue_id: venueIds.join(",") || "",
            platform_id: platformIds.join(",") || "",
            w: keyword || "",
            is_new: sort === "Newest" ? "1" : "0",
            is_hot: "0",
            game_type: getGameTypeBySection(categoryId),
        },
        fetcher: ApiFetchers.refGetGameList,
        reloadDeps: [categoryId, sort, sorting, venueIds.join(","), platformIds.join(",")],
    })

    const { run } = useRequest(async () => reload(), {
        debounceWait: 500,
        manual: true,
    })

    useUpdateEffect(() => {
        if (keyword.trim().length >= 3) {
            run()
        }
        if (keyword === "") {
            run()
        }
    }, [keyword])

    useEffect(() => {
        return () => setKeyword("")
    }, [categoryId])

    return {
        categoryId,
        sort,
        keyword,
        brands,
        ary: list,
        isLoading: loading,
        hasMore: !noMore,
        providerList,
        onLoadMore: loadMore,
        setAction,
        reload,
        setKeyword,
        run,
    }
}
